from xml.etree import ElementTree
from cocos.tiles import RectMapLayer
from cocos.tiles import RectCell
from cocos.tiles import Tile

class CMap(object):
	
	def __init__(self):
		pass
	
	""" id	--	scene id
		cw	--	cell width
		ch	--	cell height
		row	--	row of cells
		col --	col of cells
	"""
	def Create(self,id,cw,ch,row,col):
		cells=[[RectCell(col,row,cw,ch,{},None) for c in xrange(col)] for r in xrange(row) ]
		self.m_RectMap=RectMapLayer("level0",128,128,cells,(0,0,0),{})
		self.m_Layers=[]
	
	def AddImageLayer(self,fn,z):
		self.m_Layers.append((fn,z))

	def Save(self,fn):
		root=ElementTree.Element("scene")
		root.tail="\n"
		self.m_RectMap._as_xml(root)
		for iNum,layer in enumerate(self.m_Layers):
			ElementTree.SubElement(root,"imagelayer",id="layer%d"%iNum,file=layer[0],z=str(layer[1]))
		tree=ElementTree.ElementTree(root)
		tree.write(fn)

	def Load(self,fn):
		tree=ElementTree.ElementTree()
		tree.parse(fn)
		root=tree.getroot()
		self.m_Layers=[]
		for layer_node in root.findall("./imagelayer"):
			self.m_Layers.append((layer_node.get("file"),int(layer_node.get("z"))))
		node_rm=root.find("./rectmap")
		id_rm=node_rm.get("id")
		origin=map(int,node_rm.get("origin").split(","))
		cw,ch=map(int,node_rm.get("tile_size").split("x"))
		cells=[]
		for col,column in enumerate(node_rm.findall("./column")):
			colcells=[]
			cells.append(colcells)
			for row,cell in enumerate(column.findall("./cell")):
				c=RectCell(col,row,cw,ch,{},Tile("None",{},None))
				for prop in cell.findall("./property"):
					c[prop.get("name")]=prop.get("value")
				colcells.append(c)
		self.m_RectMap=RectMapLayer(id_rm,cw,ch,cells,origin,{})

	def GenBarSpriteInfo(self):
		sprites=[]
		cells=self.m_RectMap.cells
		tBars=("top","left","right","bottom")
		for row,r_cells in enumerate(cells):
			c_sprites=[]
			sprites.append(c_sprites)
			for col,cell in enumerate(r_cells):
				sp=[]
				for b in tBars:
					if not b in cell.properties:
						continue
					sp.append(b)
				c_sprites.append(sp)
		return sprites


